import logo from "@/assets/logo.png"
import "./index.scss"
import { Form, Input, Checkbox, Button, message } from "antd"
import { loginAysnc } from "@/store/slice/userinfo.slice"
import { useDispatch } from "react-redux"
import { useHistory } from "react-router-dom"
const Login = () => {
  const dispatch = useDispatch()
  const history = useHistory()
  const onFinish = async (values) => {
    try {
      // 此时拿到了整个表单的数据- 实现登录操作
      await dispatch(loginAysnc(values)) // redux 的dispatch派发
      // await意味着里面所有的逻辑都正常执行了
      message.success("登录成功")
      // 跳转到主页
      history.replace("/home")
    } catch (error) {
      message.error("用户名或者密码错误")
    }
  }

  return (
    <div className="login">
      <div className="login-container">
        <img className="login-logo" src={logo} alt="" />
        {/* 登录表单 */}
        <Form
          validateTrigger="onBlur"
          // 给一些默认值-为了开发方便-正常系统是不可能给这些数据的
          initialValues={{
            mobile: "13911111111",
            code: "246810",
            isAgree: true,
          }}
          onFinish={onFinish}
        >
          <Form.Item
            name="mobile"
            rules={[
              { required: true, message: "手机号不能为空" },
              {
                pattern: /^1[3-9]\d{9}$/,
                message: "手机号格式不正确",
              },
            ]}
          >
            <Input placeholder="请输入手机号"></Input>
          </Form.Item>
          <Form.Item
            name="code"
            rules={[
              { required: true, message: "验证码不能为空" },
              {
                pattern: /^\d{6}$/,
                message: "验证格式不正确",
              },
            ]}
          >
            <Input placeholder="请输入验证码"></Input>
          </Form.Item>
          <Form.Item
            name="isAgree"
            rules={[
              {
                validator(rule, value) {
                  // 当value 为false时，不能允许校验通过
                  if (value) {
                    return Promise.resolve() // 表示执行成功
                  }
                  return Promise.reject(new Error("未同意用户的协议条款"))
                },
              },
            ]}
            valuePropName="checked"
          >
            <Checkbox>我已阅读并同意「用户协议」和「隐私条款」</Checkbox>
          </Form.Item>
          <Form.Item>
            <Button type="primary" block htmlType="submit">
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}
export default Login
